package Fitter_my;

import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import bean.User;

import java.io.IOException;

@WebFilter(
        filterName = "AuthFilter",  // 与原 web.xml 中的 filter-name 一致，便于识别
        urlPatterns = "/*"          // 与原 web.xml 中的 url-pattern 一致，拦截所有请求
)// 拦截所有请求，可根据需要改成 /secure/* 或其他路径
public class AuthFilter implements Filter {
    private static final Logger logger = LoggerFactory.getLogger(AuthFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("Filter 开始工作");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        String uri = req.getRequestURI();
        if (uri.contains("/login") || uri.contains("/captcha") ||
                // 公开页与静态资源放行
                uri.startsWith(req.getContextPath() + "/articles") ||
                uri.endsWith(".css") || uri.endsWith(".js") || uri.endsWith(".jpg") ||
                uri.endsWith(".png") || uri.endsWith(".gif") || uri.endsWith(".woff2") ||
                uri.endsWith(".ttf") || uri.endsWith(".html") || uri.endsWith(".jsp")) {
            chain.doFilter(request, response);
            return;
        }
        // 检查 Session 中是否有登录用户
        HttpSession session = req.getSession(false);
        User user = null;
        if (session != null) {
            user = (User) session.getAttribute("user");
        }
        logger.info("对session传递的对象进行检查");
        if (session != null && user != null) {
            logger.info("检查成功，用户名为"+ user.getUsername());
            chain.doFilter(request, response); // 已登录，放行
        } else {
            // 未登录，跳转到登录页面（前端也可用 Ajax 检查）
            resp.sendRedirect(req.getContextPath() + "/fail.html");
        }
    }

    @Override
    public void destroy() {
        logger.info("销毁session");
    }
}
